<template>
  <a-modal
    v-model:open="visible"
    title="活码预览"
    width="700px"
    class="qrcode-preview-modal"
    :maskClosable="true"
    :destroyOnClose="true"
  >
    <div class="qrcode-preview-container">
      <div class="template-selector">
        <!-- 左侧模板选择 -->
        <div class="template-tabs">
          <div
            v-for="template in templates"
            :key="template.id"
            :class="['template-tab', { active: activeTemplate === template.id }]"
            @click="activeTemplate = template.id"
          >
            <div class="tab-preview">
              <div :class="['mini-qr', template.class]"></div>
            </div>
            <div class="tab-info">
              <div class="tab-name">{{ template.name }}</div>
              <div class="tab-desc">{{ template.description }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧二维码展示区域 -->
      <div class="qrcode-display" ref="qrcodeDisplayArea">
        <div :class="['qrcode-template', getCurrentTemplate().class]">
          <!-- 模板1: 经典商务 -->
          <div v-if="activeTemplate === 'classic'" class="template-classic">
            <div class="brand-header">
              <h2 class="company-name">{{ qrcodeData.qrCodeName || 'AnyPay' }}</h2>
              <p class="company-slogan">安全便捷的支付体验</p>
            </div>
            <div class="qrcode-wrapper">
              <qrcode-vue
                :value="qrcodeUrl"
                :size="180"
                level="H"
                class="qrcode-image"
              />
            </div>
            <div class="payment-methods">
              <div class="method-item">
                <img src="" alt="微信支付" />
                <span>微信支付</span>
              </div>
              <div class="method-item">
                <img src="" alt="支付宝" />
                <span>支付宝</span>
              </div>
              <div class="method-item">
                <img src="" alt="云闪付" />
                <span>云闪付</span>
              </div>
            </div>
          </div>

          <!-- 模板2: 时尚渐变 -->
          <div v-else-if="activeTemplate === 'gradient'" class="template-gradient">
            <div class="gradient-bg">
              <div class="brand-header">
                <h2 class="company-name">{{ qrcodeData.qrCodeName || 'AnyPay' }}</h2>
                <p class="company-slogan">创新支付，引领未来</p>
              </div>
              <div class="qrcode-wrapper">
                <div class="qrcode-frame">
                  <qrcode-vue
                    :value="qrcodeUrl"
                    :size="160"
                    level="H"
                    class="qrcode-image"
                  />
                </div>
              </div>
            </div>
            <div class="payment-methods gradient-methods">
              <div class="method-item">
                <span class="method-icon wechat">💬</span>
                <span>微信</span>
              </div>
              <div class="method-item">
                <span class="method-icon alipay">💰</span>
                <span>支付宝</span>
              </div>
              <div class="method-item">
                <span class="method-icon unionpay">💳</span>
                <span>云闪付</span>
              </div>
            </div>
          </div>

          <!-- 模板3: 简约现代 -->
          <div v-else-if="activeTemplate === 'minimal'" class="template-minimal">
            <div class="minimal-container">
              <div class="brand-section">
                <div class="company-logo">{{ (qrcodeData.qrCodeName || 'AnyPay').charAt(0) }}</div>
                <h3 class="company-name">{{ qrcodeData.qrCodeName || 'AnyPay' }}</h3>
              </div>
              <div class="qrcode-section">
                <qrcode-vue
                  :value="qrcodeUrl"
                  :size="140"
                  level="H"
                  class="qrcode-image"
                />
              </div>
              <div class="payment-badges">
                <span class="badge wechat">微信</span>
                <span class="badge alipay">支付宝</span>
                <span class="badge unionpay">云闪付</span>
              </div>
            </div>
          </div>

          <!-- 模板4: 品牌突出 -->
          <div v-else-if="activeTemplate === 'brand'" class="template-brand">
            <div class="brand-showcase">
              <div class="brand-banner">
                <div class="brand-logo-large">{{ (qrcodeData.qrCodeName || 'AnyPay').substring(0, 2) }}</div>
                <div class="brand-info">
                  <h1 class="brand-title">{{ qrcodeData.qrCodeName || 'AnyPay' }}</h1>
                  <p class="brand-tagline">专业支付解决方案</p>
                </div>
              </div>
              <div class="qrcode-area">
                <div class="qr-container">
                  <qrcode-vue
                    :value="qrcodeUrl"
                    :size="150"
                    level="H"
                    class="qrcode-image"
                  />
                  <div class="scan-tip">扫码支付</div>
                </div>
              </div>
              <div class="supported-payments">
                <div class="payment-row">
                  <div class="payment-icon wechat-brand">🟢</div>
                  <div class="payment-icon alipay-brand">🔵</div>
                  <div class="payment-icon unionpay-brand">🟠</div>
                </div>
                <p class="support-text">支持微信、支付宝、云闪付</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 页脚下载按钮 -->
    <template #footer>
      <div class="modal-footer">
        <a-button
          type="primary"
          @click="downloadQrcode"
          :loading="isDownloading"
          class="download-btn-footer"
        >
          <template #icon><DownloadOutlined /></template>
          下载
        </a-button>
      </div>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { DownloadOutlined } from '@ant-design/icons-vue'
import QrcodeVue from 'qrcode.vue'
import html2canvas from 'html2canvas'
import { message } from 'ant-design-vue'
import type { SuantaiQrcode } from './types'
import { apiGetSignedUrl } from './api'

interface Template {
  id: string
  name: string
  description: string
  class: string
}

const visible = ref(false)
const qrcodeData = reactive<Partial<SuantaiQrcode>>({})
const activeTemplate = ref('classic')
const qrcodeDisplayArea = ref<HTMLElement | null>(null)
const isDownloading = ref(false)
const qrcodeUrl = ref('')

// 模板配置
const templates: Template[] = [
  {
    id: 'classic',
    name: '经典商务',
    description: '专业稳重',
    class: 'classic-style'
  },
  {
    id: 'gradient',
    name: '时尚渐变',
    description: '现代时尚',
    class: 'gradient-style'
  },
  {
    id: 'minimal',
    name: '简约现代',
    description: '简洁清爽',
    class: 'minimal-style'
  },
  {
    id: 'brand',
    name: '品牌突出',
    description: '品牌展示',
    class: 'brand-style'
  }
]

// 获取当前模板
const getCurrentTemplate = () => {
  return templates.find(t => t.id === activeTemplate.value) || templates[0]
}

// 显示预览弹窗
const showPreview = async (record: SuantaiQrcode) => {
  Object.assign(qrcodeData, record)
  if (!qrcodeData.qrCodeId) {
    message.error("二维码ID不存在，无法生成预览");
    qrcodeUrl.value = ''
    return;
  }

  visible.value = true;
  qrcodeUrl.value = ''; // 重置URL，显示加载状态

  try {
    // 拦截器会处理成功/失败，如果await成功，res就是后端返回的ApiResponse对象
    const res = await apiGetSignedUrl(qrcodeData.qrCodeId);
    // 我们进行类型断言来辅助TypeScript
    qrcodeUrl.value = (res as { data: string }).data;
  } catch (error) {
    // 错误通知已由拦截器处理，这里只需处理UI状态
    qrcodeUrl.value = '';
    console.error("请求二维码链接失败:", error); // 方便调试
  }
}

// 下载二维码
const downloadQrcode = async () => {
  if (!qrcodeDisplayArea.value) {
    message.error('无法找到预览区域');
    return;
  }

  const templateName = getCurrentTemplate().name
  const targetElement = qrcodeDisplayArea.value.querySelector('.qrcode-template > div');

  if (!targetElement) {
    message.error('无法找到模板内容');
    return;
  }

  isDownloading.value = true;
  message.loading({ content: '正在生成图片...', key: 'download' });

  try {
    const canvas = await html2canvas(targetElement as HTMLElement, {
      useCORS: true,
      backgroundColor: null, // 保持渐变背景
      scale: 3, // 提高分辨率
    });

    const dataUrl = canvas.toDataURL('image/png');
    const link = document.createElement('a');
    link.href = dataUrl;
    link.download = `活码预览-${qrcodeData.qrCodeName}-${templateName}.png`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    message.success({ content: '下载成功!', key: 'download', duration: 2 });
  } catch (error) {
    console.error('下载失败:', error);
    message.error({ content: '图片生成失败，请稍后重试', key: 'download', duration: 2 });
  } finally {
    isDownloading.value = false;
  }
}

// 暴露方法给父组件调用
defineExpose({
  showPreview
})
</script>

<style scoped>
.qrcode-preview-modal :deep(.ant-modal-content) {
  border-radius: 16px;
  overflow: hidden;
}

.qrcode-preview-modal :deep(.ant-modal-header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-bottom: none;
  padding: 20px 24px;
}

.qrcode-preview-modal :deep(.ant-modal-title) {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.qrcode-preview-modal :deep(.ant-modal-close) {
  color: white;
  opacity: 0.8;
}

.qrcode-preview-container {
  display: flex;
  height: 600px;
  background: #f8f9fa;
}

/* 左侧模板选择器 */
.template-selector {
  width: 200px;
  background: white;
  border-right: 1px solid #f0f0f0;
  padding: 8px 0;
}

.template-tabs {
  /* 移除.tab-header的样式和结构 */
}

.template-tab {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s ease-in-out;
  border-right: 3px solid transparent;
  margin: 4px 0;
}

.template-tab:hover {
  background: #fafafa;
}

.template-tab.active {
  background: #e6f7ff;
  border-right-color: #1890ff;
  color: #1890ff;
}

.tab-preview {
  width: 32px;
  height: 32px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  background: #f0f0f0;
}

.mini-qr {
  width: 20px;
  height: 20px;
  background: #333;
  border-radius: 2px;
}

.mini-qr.classic-style {
  background: linear-gradient(45deg, #333, #666);
}

.mini-qr.gradient-style {
  background: linear-gradient(45deg, #667eea, #764ba2);
}

.mini-qr.minimal-style {
  background: #1890ff;
}

.mini-qr.brand-style {
  background: linear-gradient(45deg, #ff6b6b, #feca57);
}

.tab-info {
  flex: 1;
}

.tab-name {
  font-size: 13px;
  font-weight: 500;
  color: #333;
  margin-bottom: 2px;
}

.tab-desc {
  font-size: 11px;
  color: #999;
}

/* 右侧二维码展示区域 */
.qrcode-display {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24px;
  background: #f8f9fa; /* 增加淡色背景 */
}

.qrcode-template {
  flex-shrink: 0;
}

/* 模板1: 经典商务 */
.template-classic {
  background: white;
  border-radius: 12px;
  padding: 32px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  max-width: 300px;
}

.template-classic .brand-header {
  margin-bottom: 24px;
}

.template-classic .company-name {
  font-size: 24px;
  font-weight: 700;
  color: #333;
  margin: 0 0 8px 0;
}

.template-classic .company-slogan {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.template-classic .qrcode-wrapper {
  margin: 24px 0;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.template-classic .payment-methods {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
}

.template-classic .method-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.template-classic .method-item img {
  width: 24px;
  height: 24px;
}

.template-classic .method-item span {
  font-size: 11px;
  color: #666;
}

/* 模板2: 时尚渐变 */
.template-gradient {
  max-width: 340px;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.gradient-bg {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 32px;
  text-align: center;
  color: white;
}

.template-gradient .company-name {
  font-size: 22px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.template-gradient .company-slogan {
  font-size: 13px;
  opacity: 0.9;
  margin: 0 0 24px 0;
}

.template-gradient .qrcode-frame {
  background: white;
  padding: 16px;
  border-radius: 12px;
  display: inline-block;
}

.gradient-methods {
  background: white;
  padding: 20px;
  display: flex;
  justify-content: space-around;
}

.gradient-methods .method-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
}

.method-icon {
  font-size: 20px;
}

.gradient-methods span:last-child {
  font-size: 12px;
  color: #666;
}

/* 模板3: 简约现代 */
.template-minimal {
  max-width: 280px;
}

.minimal-container {
  background: white;
  border-radius: 8px;
  padding: 24px;
  text-align: center;
  border: 1px solid #e8e8e8;
}

.brand-section {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 24px;
}

.company-logo {
  width: 40px;
  height: 40px;
  background: #1890ff;
  color: white;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: 600;
}

.template-minimal .company-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.qrcode-section {
  margin: 24px 0;
}

.payment-badges {
  display: flex;
  justify-content: center;
  gap: 8px;
  margin-top: 20px;
}

.badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
}

.badge.wechat {
  background: #e6f7e6;
  color: #52c41a;
}

.badge.alipay {
  background: #e6f7ff;
  color: #1890ff;
}

.badge.unionpay {
  background: #fff7e6;
  color: #fa8c16;
}

/* 模板4: 品牌突出 */
.template-brand { max-width: 350px; }
.brand-showcase {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}
.brand-banner {
  background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%);
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  color: white;
}
.brand-logo-large {
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: 700;
}
.brand-title {
  font-size: 20px;
  font-weight: 700;
  margin: 0 0 4px 0;
}
.brand-tagline { font-size: 13px; opacity: 0.9; margin: 0; }
.qrcode-area { padding: 32px 24px; text-align: center; }
.qr-container { display: inline-block; }
.scan-tip { margin-top: 12px; font-size: 12px; color: #666; }
.supported-payments {
  padding: 20px 24px;
  background: #f8f9fa;
  text-align: center;
  border-top: 1px solid #f0f0f0;
}
.payment-row {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-bottom: 8px;
}
.payment-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}
.support-text { font-size: 12px; color: #666; margin: 0; }
.modal-footer { text-align: right; }
.download-btn-footer {
  border-radius: 6px;
  font-weight: 500;
}
</style>